package com.ruoyi.ring.service.impl;

import cn.hutool.core.convert.Convert;
import com.alibaba.fastjson2.JSONArray;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.TimeUnitEnums;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.bean.Builder;
import com.ruoyi.ring.domain.DailyTags;
import com.ruoyi.ring.domain.dto.GeneralSecondDTO;
import com.ruoyi.ring.domain.vo.*;
import com.ruoyi.ring.mapper.DailyTagsMapper;
import com.ruoyi.ring.service.IEventSubtotalSecondService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.ZoneId;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.function.Function;
import java.util.stream.Collectors;

@Service
public class EventSubtotalSecondServiceImpl implements IEventSubtotalSecondService {
    @Resource
    private DailyTagsMapper dailyTagsMapper;

    @Override
    public List<CalendarResultVO> queryCalendarList(GeneralSecondDTO secondDTO) {
        List<DailyTags> dailyTagsList = dailyTagsMapper.selectDailyTagsList(Builder.of(DailyTags::new).with(DailyTags::setUserId,SecurityUtils.getUserId()).build());
        List<CalendarResultVO> resultVOS = Convert.toList(CalendarResultVO.class,dailyTagsList);
        ZoneId zoneId = ZoneId.systemDefault();
        List<CalendarResultVO> list = resultVOS.stream()
                .collect(Collectors.toMap(
                        vo -> vo.getDailyValue().toInstant().atZone(zoneId).toLocalDate(),
                        Function.identity(),
                        (existing, replacement) -> existing
                ))
                .values()
                .stream()
                // 使用Comparator.comparing指定按日期正序
                .sorted(Comparator.comparing(vo -> vo.getDailyValue().toInstant().atZone(zoneId).toLocalDate()))
                .collect(Collectors.toList());
        return list;
    }

    @Override
    public AjaxResult queryEventSubtotalList(GeneralSecondDTO secondDTO) {
        EventDayListVO dayListVO = new EventDayListVO();

        EventListVO eventListVO = new EventListVO();
        List<EventListVO.EventDayVO> eventDayVOS = new ArrayList<>();

        secondDTO.setUserId(SecurityUtils.getUserId());
        List<GeneralGroupVO> groupVOList = dailyTagsMapper.queryRingEventInfoList(secondDTO);
        String dateStart = "";
        String dateEnd = "";
        String recordDate = "";
        String weekName = "";
        for (GeneralGroupVO group : groupVOList) {
            List<DailyTagsInfoVo> voList = new ArrayList<>();
            if (!TimeUnitEnums.DAY.getCode().equals(secondDTO.getType())) {
                dateStart = group.getDateStart() + "，" + DateUtils.getChineseWeekday(group.getDateStart());
                dateEnd = group.getDateEnd() + "，" + DateUtils.getChineseWeekday(group.getDateEnd());
            }
            recordDate = group.getDailyValue();
            weekName = group.getWeekName();
            String groupData = group.getGroupData(); // 包含多条记录的JSON数组
            // 解析JSON数组为具体的实体类（假设有子实体类 BloodOxygenDetail）
            if (groupData != null) {
                voList.addAll(queryDailyTagsInfoVoList(groupData));
            }
            voList = voList.stream().sorted(Comparator.comparingLong(DailyTagsInfoVo::getId)).collect(Collectors.toList());
            if (TimeUnitEnums.DAY.getCode().equals(secondDTO.getType())) {
                List<EventDayListVO.EventVO> eventVOS = new ArrayList<>();
                dayListVO.setRecordDate(recordDate);
                dayListVO.setWeekName(weekName);
                for (DailyTagsInfoVo vo : voList) {
                    eventVOS.add(queryEventDayList(vo));
                }
                dayListVO.setEventVOS(eventVOS);
                return AjaxResult.success(dayListVO);
            } else{
                eventListVO.setDateStart(dateStart);
                eventListVO.setDateEnd(dateEnd);

                EventListVO.EventDayVO eventDayVO = new EventListVO.EventDayVO();
                eventDayVO.setRecordDate(recordDate);
                eventDayVO.setWeekName(weekName);
                List<EventListVO.EventDayVO.EventVO> eventVOS = new ArrayList<>();
                for (DailyTagsInfoVo vo : voList) {
                    eventVOS.add(queryEventList(vo));
                }
                eventDayVO.setEventVOS(eventVOS);
                eventDayVOS.add(eventDayVO);
                eventListVO.setEventDayVOS(eventDayVOS);
            }
        }
        if(TimeUnitEnums.DAY.getCode().equals(secondDTO.getType())){
            return AjaxResult.success(dayListVO);
        }else {
            return AjaxResult.success(eventListVO);
        }
    }
    /** json字符串转换集合 */
    public List<DailyTagsInfoVo> queryDailyTagsInfoVoList(String groupData){
        JSONArray jsonArray = JSONArray.parseArray(groupData);
        return jsonArray.toJavaList(DailyTagsInfoVo.class);
    }
    /** 组合天信息 */
    public EventDayListVO.EventVO queryEventDayList(DailyTagsInfoVo vo){
        EventDayListVO.EventVO eventVO = new EventDayListVO.EventVO();
        eventVO.setEventInfo(vo.getEventInfo());
        eventVO.setRecordScores(vo.getRecordScores());
        eventVO.setRecordTime(DateUtils.convertDateTimeToHHMM(vo.getRecordTime()));
        return eventVO;
    }

    /** 组合周/月信息 */
    public EventListVO.EventDayVO.EventVO  queryEventList(DailyTagsInfoVo vo){
        EventListVO.EventDayVO.EventVO eventVO = new EventListVO.EventDayVO.EventVO();
        eventVO.setEventInfo(vo.getEventInfo());
        eventVO.setRecordScores(vo.getRecordScores());
        eventVO.setRecordTime(DateUtils.convertDateTimeToHHMM(vo.getRecordTime()));
        return eventVO;
    }
}
